/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package servlet;

import javax.ejb.EJB;
import session.TX.*;
import exception.ExistException;
import exception.OccupiedException;
import Helper.Seats;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author User
 */
@WebServlet(name = "AddNewLayoutController", urlPatterns = {"/AddNewLayoutController"})
public class AddNewLayoutController extends HttpServlet {
    @EJB
    private PerformanceTicketingSBRemote etbr;

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
                
        response.setContentType("text/plain");
        PrintWriter out = response.getWriter();
        //request.getSession().setAttribute("A", "Success");

        System.out.println("Entered layout controller:");
        System.out.println("hiddenEmpty: " + request.getParameter("hiddenEmpty").toString());
        System.out.println("hiddenRows: " + request.getParameter("hiddenRows").toString());
        System.out.println("hiddenColumns: " + request.getParameter("hiddenColumns").toString());
        System.out.println("hiddenOccupied: " + request.getParameter("hiddenOccupied").toString());
        System.out.println("cost: " + request.getParameter("cost").toString());
        System.out.println("areaName: " + request.getParameter("areaname").toString());
        System.out.println("ids: " + request.getParameter("ids").toString());
        System.out.println("cpage: " + request.getParameter("cpage").toString());
        String getRows = request.getParameter("hiddenRows").toString();
        String getColumns = request.getParameter("hiddenColumns").toString();
        String getOccupied = request.getParameter("hiddenOccupied").toString();
        String getEmpty = request.getParameter("hiddenEmpty").toString();
        Double cost = Double.valueOf(request.getParameter("cost").toString());
        String areaName = request.getParameter("areaname").toString();
        Long showId = Long.valueOf(request.getParameter("ids").toString());
        String cpage = String.valueOf(request.getParameter("cpage").toString());
        // sets for columns
        List<Integer> column = new ArrayList<Integer>();
        getColumns = getColumns.substring(0, getColumns.indexOf(";;") + 1);
        while (!(getColumns.matches(""))) {
            int a = Integer.parseInt(getColumns.substring(0, getColumns.indexOf(";")));
            column.add(a);
            getColumns = getColumns.substring(getColumns.indexOf(";") + 1, getColumns.length());
        }
        System.out.println(column.toString());
        // sets for rows
        List<String> row = new ArrayList<String>();
        String b = new String();
        b = getRows.substring(0, getRows.indexOf(";;;"));
        while (!b.matches("")) {
            //System.out.println("start" + b);
            String c = new String();
            if (b.contains(";;")) {
                c = b.substring(0, b.indexOf(";"));
                //System.out.println(c);
                row.add(c);
                b = b.substring(b.indexOf(";;") + 2, b.length());
                //System.out.println("end" + b);
            } else {
                if (b.contains(";")) {
                    c = b.substring(0, b.indexOf(";"));
                    row.add(c);
                } else {
                    row.add(b);
                }
                b = "";
            }
            getRows = "";
        }
        //System.out.println(row.toString());
        // sets occupied status
        Boolean[][] occupy = new Boolean[row.size()][column.size()];
        for (int i = 0; i < row.size(); i++) {
            for (int j = 0; j < column.size(); j++) {
                occupy[i][j] = false;
            }
        }
        // sets empty status
        Boolean[][] empty = new Boolean[row.size()][column.size()];
        //System.out.println(row.size());
        //System.out.println(column.size());
        int countI = 0;
        int countJ = 0;
        char[] getEmptyTemp = getEmpty.toCharArray();
        String check = new String();
        for (int i = 0; i < getEmptyTemp.length; i++) {
            if (getEmptyTemp[i] != ';') {
                if (getEmptyTemp[i] == 'T') {
                    empty[countI][countJ] = true;
                } else {
                    empty[countI][countJ] = false;
                }
                check = "";
                countJ++;
            } else {
                check += getEmptyTemp[i];
                if (check.equalsIgnoreCase(";;")) {
                    countI++;
                    countJ = 0;
                }
            }
        }
        for (int i = 0; i < empty.length; i++) {
            for (int j = 0; j < empty[i].length; j++) {
                System.out.println(empty[i][j]);
            }
        }
        System.out.println(row.toString());
        System.out.println(column.toString());
        int numRow = row.size();
        int numColumn = column.size();
        Seats[][] areaSeats = new Seats[numRow][numColumn];
        System.out.println("Came Here with rows and columns respectively: " + numRow + " " + numColumn);
        for (int i = 0; i < numRow; i++) {
            for (int j = 0; j < numColumn; j++) {
                Seats se = new Seats();
                se.setRow(row.get(i));
                se.setColumn(column.get(j));
                se.setReserved(occupy[i][j]);
                se.setEmpty(empty[i][j]);
                System.out.println(i + " " + j);
                System.out.println(row.get(i) + " " + column.get(j) + " " + occupy[i][j] + " " + empty[i][j]);
                areaSeats[i][j] = se;
            }
        }
        /*for(int i = 0; i < numRow; i++){
        for(int j = 0; j < numColumn; j++){
        System.out.println(areaSeats[i][j].getRow() + areaSeats[i][j].getColumn());
        }
        }*/
        System.out.println("cpage: " + cpage);
        
        try {
            String statusMessage = new String();
            if (cpage.equalsIgnoreCase("add")) {
                System.out.println("Add Area:");
                etbr.addArea(areaName, areaSeats, cost, showId);
                statusMessage = "Success: " + areaName + " added into show.";
            } else if (cpage.equalsIgnoreCase("modify")) {
                System.out.println("Modify Area:");
                etbr.modifyArea(areaName, areaSeats, cost, showId);
                statusMessage = "Success: " + areaName + " modified successfully.";
            }
            out.print(statusMessage);
            out.flush();
            out.close();
            System.out.println("AddLayout Result: " + statusMessage);
        } catch (ExistException e) {
            System.out.println(e.getMessage());
            String statusMessage = "Error: " + e.getMessage();
            out.print(statusMessage);
            out.flush();
            out.close();
            System.out.println("AddLayout Result: " + statusMessage);
        } catch (OccupiedException o) {
            System.out.println(o.getMessage());
            String statusMessage = "Error: " + o.getMessage();
            out.print(statusMessage);
            out.flush();
            out.close();
            System.out.println("AddLayout Result: " + statusMessage);
        } catch (Exception ex) {
            out.print("Unknown Error");
            out.flush();
            out.close();
            String statusMessage = "Error: " + ex.getMessage();
            System.out.println("AddLayout Result: " + statusMessage);
        }
        /*String success = new String();
        success = "success";
        shb.addAreaStatus(success);*/

        /*out.print("Error");
        out.flush();
        out.close();*/
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
